<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="formRef"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
			>
				<!-- <el-form-item class="flex-row-container">
					<el-input
						v-model="queryData.searchMemberName"
						class="input-with-select"
						:placeholder="$t('common.please_enter')"
						clearable
						size="medium"
						style="width: 330px"
					>
						<el-select
							slot="prepend"
							v-model="queryData.memberType"
							:placeholder="$t('common.please_choose')"
							style="width: 110px"
						>
							<el-option label="代理账号" :value="6"></el-option>
							<el-option label="会员账号" :value="5"></el-option>
						</el-select>
					</el-input>
				</el-form-item>
				<el-form-item
					label="账单周期"
					class="flex-row-container"
					label-width="77px"
				>
					<el-select
						v-model="queryData.billEndDate"
						placeholder="请选择"
						style="width: 350px"
						@change="changeBillEndDate"
					>
						<el-option
							v-for="item in billDateList"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item> -->

				<div class="flex-box">
					<el-form-item class="flex-row-container">
						<!-- <el-button
							type="primary"
							icon="el-icon-search"
							size="medium"
							@click="search"
						>
							{{ $t('common.search') }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							size="medium"
							@click="reset"
						>
							{{ $t('common.reset') }}
						</el-button> -->
						<el-button
							v-if="hasPermission('90750088')"
							type="warning"
							icon="el-icon-download"
							size="medium"
							:loading="exportBtnLoading"
							@click="handleExportExcel"
						>
							{{ $t('common.export') }}
						</el-button>
						<el-button
							type="success"
							icon="el-icon-sort"
							:disabled="loading"
							size="medium"
							@click="openColSettings"
						>
							{{ $t('common.row_set') }}
						</el-button>
					</el-form-item>
				</div>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				ref="elTable"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				class="small-size-table"
				:max-height="tableHeight"
				:data="tableData"
				v-bind="$attrs"
				v-on="$listeners"
				:header-cell-style="getRowClass"
				highlight-current-row
			>
				<el-table-column
					v-for="(item, index) in newCol"
					:key="'column_' + index"
					:prop="newCol[index].prop"
					:align="item.alignCenter"
					:label="item.label"
					:min-width="item.minWidth"
					:fixed="item.isFixed"
					:sortable="item.isSortColumn"
					:show-overflow-tooltip="item.isShowTip"
				>
					<template slot="header">
						<span v-if="item.itemTipContent">
							{{ item.label }}
							<el-tooltip
								class="item"
								effect="dark"
								:content="item.itemTipContent"
								placement="top-start"
							>
								<i class="el-icon-question"></i>
							</el-tooltip>
						</span>
						<span v-else>
							{{ item.label }}
						</span>
					</template>
					<template slot-scope="{ row, $index }">
						<div v-if="item.solt === 'numberSolt'">
							<span
								:style="
									handleNumberColor(row[newCol[index].prop])
								"
							>
								{{
									handleNumber(
										'USDT',
										row[newCol[index].prop],
										2,
										true,
										true
									)
								}}
							</span>
						</div>
						<div v-if="item.solt === 'noColorNumberSolt'">
							<span>
								{{
									handleNumber(
										'USDT',
										row[newCol[index].prop],
										2,
										true,
										true
									)
								}}
							</span>
						</div>
						<div v-if="item.solt === 'betOrderIdSlot'">
							{{ row.betOrderId || row.id || '-' }}
						</div>
						<div v-if="item.solt === 'accountTypeSlot'">
							{{ typeFilter(row.accountType, 'accountType') }}
						</div>
						<div v-if="item.solt === 'businessModelSlot'">
							{{
								row[newCol[index].prop] == 1
									? '现金模式'
									: '信用模式'
							}}
						</div>
						<div v-if="item.solt === 'betTypeSlot'">
							{{ parentBetTypes[row.betType] || '-' }}
						</div>
						<div v-if="item.solt === 'validBetAmountSlot'">
							<money
								v-if="row.obBetStatus === 1"
								:value="`${handleCurrency(row.memberCurrency)}
						${handleNumber(row.memberCurrency, row.validBetAmount)}`"
							/>
							<span v-else>$0</span>
						</div>
						<div v-if="item.solt === 'obBetStatusSlot'">
							<span
								v-if="row.obBetStatus === 0"
								class="deleteRgba"
							>
								{{
									typeFilter(row.obBetStatus, 'betStatusType')
								}}
							</span>
							<span
								v-else-if="row.obBetStatus === 1"
								class="normalRgba"
							>
								{{
									typeFilter(row.obBetStatus, 'betStatusType')
								}}
							</span>
							<span
								v-else-if="row.obBetStatus === 2"
								class="disableRgba"
							>
								{{
									typeFilter(row.obBetStatus, 'betStatusType')
								}}
							</span>
							<span v-else>-</span>
						</div>
						<div v-if="item.solt === 'obSettleCountSlot'">
							<span
								v-if="row.obBetStatus === 1"
								:style="{
									color: row.obSettleCount > 0 ? 'red' : ''
								}"
							>
								{{ formatObSettleCount(row.obSettleCount) }}
							</span>
							<span v-else>-</span>
						</div>
						<div v-if="item.solt === 'betContentSlot'">
							<span v-if="row.gameTypeId < -1">
								<el-link
									type="primary"
									@click="lookBetting(row, $index)"
								>
									{{ row.betContent }}
								</el-link>
							</span>
							<span v-else>{{ row.betContent || '-' }}</span>
						</div>
						<div v-if="item.solt === 'obDeviceTypeSlot'">
							<span v-if="row.obDeviceType === '其他'">
								{{ row.obDeviceType }}
							</span>
							<span v-else>
								{{
									typeFilter(
										row.obDeviceType,
										'loginDeviceType'
									)
								}}
							</span>
						</div>
						<div v-if="item.solt === 'statusSlot'">
							<span v-if="row.status == 0" style="color: red">
								匹配失败
							</span>
							<span v-else>-</span>
						</div>
						<span
							v-if="
								item.solt === 'operate' &&
								hasPermission('90750069')
							"
						>
							<el-link
								class="lightBlueColor"
								type="primary"
								@click="lookMsg(row, $index)"
							>
								查看详情
							</el-link>
						</span>
						<div v-if="item.solt === 'defaultSolt'">
							<span>
								{{ row[newCol[index].prop] || '-' }}
							</span>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				v-show="!!total"
				class="pageValue"
				:current-page.sync="pageNum"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size.sync="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<el-dialog
			:title="$t('common.row_set')"
			center
			:visible.sync="colSettings.visible"
			width="475px"
			class="setting-div"
		>
			<div>
				<el-link type="primary" @click="clickDel">复原缺省</el-link>
			</div>
			<div
				v-for="(value, columnName) in activityListField"
				:key="columnName"
				class="setting-div"
			>
				<el-checkbox v-model="dialogColumnData[columnName]">
					{{ columnName }}
				</el-checkbox>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="colSettings.visible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="handleOrderList">
					{{ $t('common.submit') }}
				</el-button>
			</div>
		</el-dialog>
		<!-- 详情弹窗 -->
		<chargeDialog
			v-if="chargeDialogVisible"
			:visible.sync="chargeDialogVisible"
			@handleVisible="chargeDialogVisible = false"
			:curData="curData"
			:queryData="childrenAjaxData"
		/>
		<!-- 投注详情 -->

		<el-dialog
			:title="cascading"
			:visible.sync="dialogGameVisible"
			:destroy-on-close="true"
			class="rempadding"
		>
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				size="mini"
				class="small-size-table"
				:data="gameList"
				style="width: 100%; margin: 15px 0"
				:header-cell-style="getRowClass"
			>
				<el-table-column
					prop="gameTypeName"
					align="center"
					:label="$t('member.game_id')"
				>
					<template slot-scope="scope">
						{{ scope.row.gameTypeName || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="event"
					align="center"
					:label="$t('game.game_betslip.event')"
				>
					<template slot-scope="scope">
						{{ scope.row.event || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="playName"
					align="center"
					:label="$t('game.game_betslip.playName')"
				>
					<template slot-scope="scope">
						{{ scope.row.playName || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="content"
					align="center"
					:label="$t('game.game_betslip.content')"
				>
					<template slot-scope="scope">
						{{ scope.row.content || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="marketType"
					align="center"
					:label="$t('game.game_betslip.marketType')"
				>
					<template slot-scope="scope">
						{{ scope.row.marketType || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="betAmount"
					align="center"
					:label="$t('game.game_betslip.bet_amount')"
				>
					<template slot-scope="scope">
						{{ handleCurrency(currency) }}
						{{ handleNumber(currency, scope.row.betAmount) }}
					</template>
				</el-table-column>
				<el-table-column
					prop="oddsValues"
					align="center"
					:label="$t('game.game_betslip.oddsValues')"
				>
					<template slot-scope="scope">
						{{ scope.row.oddsValues || '-' }}
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>
		<!-- 详情弹窗 -->
		<detail
			v-if="detailDialog.visible"
			:lookMsgList="lookMsgList"
			v-model="detailDialog.visible"
		/>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import summaryList from './components/summaryList'
import { getColumns } from './components/columns'
import MainContent from '@/components/MainContent/index.vue'
import chargeDialog from './components/chargeDialog'
import Money from './components/money.vue'
import gameMixins from '../mixins/index'
import Detail from './components/detail.vue'

export default {
  components: {
    MainContent,
    chargeDialog,
    Money,
    Detail
  },
  mixins: [list, gameMixins, summaryList],
  props: {
    searchData: {
      type: Object,
      default: () => { }
    },
    billDateList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dayjs,
      tableHeight: 480,
      chargeDialogVisible: false,
      otherDependenComponents: [],
      queryData: {
        merchantId: '',
        memberType: 6,
        searchMemberName: '',
        billEndDate: ''
      },
      tableData: [],
      subSummary: {},
      totalSummary: {},
      //   billDateList: [],
      loading: false,
      exportBtnLoading: false,
      curData: '',
      oldCol: [],
      childrenAjaxData: '',
      venueTypeCode: 'init',
      dialogFormVisible: false,
      currency: '',
      cascading: '',
      dialogGameVisible: false,
      dataList: {},
      betHisDetails: [],
      gameList: [],
      lookMsgList: {},
      detailDialog: {
        visible: false,
        currentRecordId: '',
        currentRecordIndex: ''
      },
      colSettings: {
        visible: false
      },
      activityListField: {},
      parentBetTypes: {},
      parentBetSubTypes: {}
    }
  },
  computed: {
    newCol() {
      return this.oldCol.map(item => {
        item.isShow = this.activityListField[item.label]
        return item
      }).filter(item => item.isShow)
    }
  },
  watch: {
    searchData: {
      handler(val) {
        this.queryData = {
          merchantId: val.merchantId,
          memberType: val.userType == '0' ? 5 : 6,
          searchMemberName: val.userName,
          billEndDate: val.billEndDate
        }
      },
      immediate: true,
      deep: true
    }

  },
  created() {
    this.oldCol = getColumns()
    this.oldCol.map(item => {
      this.activityListField[item.label] = item.isShow
    })
    this.initIndexDB('AbnormalBets', this.activityListField)
  },
  mounted() {
    this.getGameRecoedTypeSection()
    // this.getSettlementBillTimeList()
  },
  methods: {
    handlePrevOrNext(type) {
      // type 1 上一条  2下一条
      const index =
        type === 1
          ? this.detailDialog.currentRecordIndex - 1
          : this.detailDialog.currentRecordIndex + 1

      if (this.tableData[index]) {
        this.detailDialog.currentRecordIndex = index
        this.getdetailsdata(this.tableData[index], 1)
      }
    },
    // 查看详情
    lookMsg(val, index) {
      this.lookMsgList = val
      this.venueTypeCode = val.venueTypeCode
      this.detailDialog.visible = true
      this.detailDialog.currentRecordId = val.id
      this.detailDialog.currentRecordIndex = index
      this.pageScrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
      this.getdetailsdata(val, 1)
    },
    // 投注详情
    lookBetting(val) {
      this.currency = val.memberCurrency
      this.cascading = val.betContent
      this.dialogGameVisible = true
      this.getdetailsdata(val)
    },
    getdetailsdata(val, flag) {
      const data = {}
      data.id = val.id
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.dataList = {}
      this.betHisDetails = []
      // 是否重算
      if (val.obSettleCount > 0 && flag === 1 && !this.isReset) {
        this.$api
          .getResettlementGameRecordDetails(data)
          .then((res) => {
            if (res.code === 200) {
              this.betHisDetails = res.data.betHisDetails
              this.dataList = res.data
            }
            loading.close()
          })
          .catch(() => {
            loading.close()
          })
        return
      }
      this.fetchDetailApi(data)
        .then((res) => {
          if (res?.code === 200) {
            this.dataList = res.data
            this.gameList = res.data.betDetails
            this.betHisDetails = [res.data]

            if (flag === 1) {
              this.detailDialog.visible = true
              this.venueTypeCode = val.venueTypeCode || 'init'
            } else {
              this.dialogFormVisible = true
            }
            loading.close()
          }
        })
        .catch(() => {
          loading.close()
        })
    },
    // 查询注单类型
    async getGameRecoedTypeSection() {
      try {
        const res = await this.$api.getGameRecoedTypeSection()
        if (res.code === 200 && res.data) {
          res.data.forEach((item) => {
            // this.parentBetTypes[item.type] = item.desc

            if (item.subList && item.subList.length > 0) {
              this.parentBetSubTypes[item.type] = {}
              item.subList.forEach((subItem) => {
                if (subItem.type == 1) {
                  subItem.desc = '俱乐部游戏'
                }
                this.parentBetTypes[subItem.type] = subItem.desc
                this.parentBetSubTypes[item.type][
                  subItem.type
                ] = subItem.desc
              })
            }
          })
        }
      } catch (err) {
        throw err
      }
    },
    changeBillEndDate() {
      this.queryData.periodType = 6
    },
    forceUpdate(value) {
      this.$forceUpdate()
      this.queryData.searchMemberName = this.queryData.searchMemberName.replace(
        /[^A-Za-z0-9]/g,
        ''
      )
    },
    getButtonDate(val) {
      this.queryData.periodType = val
      this.queryData.billEndDate = ''
      this.queryData.cycleStartDate = ''
      this.queryData.cycleEndDate = ''
      if (val == 4) {
        this.queryData.billEndDate = 0
      } else {
        if (this.billDateList.length > 1) {
          if (val == 5) {
            this.queryData.billEndDate = 1
          } else if (val == 1) {
            this.queryData.billEndDate = this.billDateList.length - 3
          } else if (val == 2) {
            this.queryData.billEndDate = this.billDateList.length - 2
          } else if (val == 3) {
            this.queryData.billEndDate = this.billDateList.length - 1
          }
        } else {
          this.queryData.billEndDate = ''
        }
      }
      this.loadData()
    },
    // getSettlementBillTimeList() {
    //   this.loading = true
    //   const params = {
    //     pageNum: 1,
    //     pageSize: 200,
    //     periodType: 6
    //   }
    //   this.$api
    //     .proxyTeamBillPeriod(params)
    //     .then((res) => {
    //       this.loading = false
    //       if (res?.code === 200) {
    //         const { record } = res?.data
    //         this.billDateList = record.map(
    //           (item, index) => {
    //             const startTime = dayjs(String(item.periodStDate)).format('YYYY-MM-DD') + ' 00:00:00'
    //             const endTime = dayjs(String(item.periodEnDate)).format('YYYY-MM-DD') + ' 23:59:59'
    //             return {
    //               code: index,
    //               description: `${startTime} 至 ${endTime}`,
    //               periodStDate: item.periodStDate,
    //               periodEnDate: item.periodEnDate,
    //               periodStStr: startTime,
    //               periodEnStr: endTime
    //             }
    //           }
    //         )
    //         this.queryData.billEndDate = 0
    //         this.loadData()
    //       }
    //     })
    //     .catch(() => {
    //       this.loading = false
    //     })
    // },
    dialogData(row) {
      let type = 0
      if (row.shouldPaymentReceiptParentAmount > 0) {
        type = 1
      }
      this.curData = {
        ...row,
        type: type
      }
      this.chargeDialogVisible = true
    },
    loadData() {
      if (!this.billDateList.length) return
      if (!this.queryData.merchantId) {
        this.$message.warning('请选择商户')
        return
      }
      if (!this.queryData.searchMemberName) {
        if (this.queryData.memberType == '5') {
          this.$message.warning('请先输入会员账号')
        } else if (this.queryData.memberType == '6') {
          this.$message.warning('请先输入代理账号')
        }
        return
      }
      const params = {
        ...this.queryData,
        ...this.getParams()
      }
      params.netAtEnd = this.billDateList[this.queryData.billEndDate].periodEnStr
      params.netAtStart = this.billDateList[this.queryData.billEndDate].periodStStr
      if (!params.searchMemberName) {
        delete params.memberName
        delete params.parentProxyName
      } else {
        if (this.queryData.memberType == '5') {
          params.memberName = params.searchMemberName
          delete params.parentProxyName
        } else if (this.queryData.memberType == '6') {
          params.parentProxyName = params.searchMemberName
          delete params.memberName
        }
      }
      delete params.searchMemberName
      delete params.billEndDate
      delete params.memberType
      this.childrenAjaxData = JSON.parse(JSON.stringify(params))
      this.loading = true
      this.$api
        .venueAbnormalListPage(params)
        .then((res) => {
          this.loading = false
          if (res.code === 200) {
            this.tableData = []
            this.tableData = res?.data?.record || []
            this.total = res?.data?.totalRecord || 0
            this.subSummary = res?.data?.summary || {}
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    search() {
      this.pageNum = 1
      this.loadData()
    },
    reset() {
      this.pageNum = 1
      this.queryData = {
        merchantId: '',
        billEndDate: this.billDateList.length > 1 ? 0 : '',
        memberType: 6,
        searchMemberName: ''
      }
      this.loadData()
    },
    handleExportExcel() {
      if (!this.billDateList.length) return
      if (!this.queryData.merchantId) {
        this.$message.warning('请选择商户')
        return
      }
      if (!this.queryData.searchMemberName) {
        if (this.queryData.memberType == '5') {
          this.$message.warning('请先输入会员账号')
        } else if (this.queryData.memberType == '6') {
          this.$message.warning('请先输入代理账号')
        }
        return
      }
      const params = {
        ...this.queryData,
        ...this.getParams()
      }
      params.netAtEnd = this.billDateList[this.queryData.billEndDate].periodEnStr
      params.netAtStart = this.billDateList[this.queryData.billEndDate].periodStStr
      if (!params.searchMemberName) {
        delete params.memberName
        delete params.parentProxyName
      } else {
        if (this.queryData.memberType == '5') {
          params.memberName = params.searchMemberName
          delete params.parentProxyName
        } else if (this.queryData.memberType == '6') {
          params.parentProxyName = params.searchMemberName
          delete params.memberName
        }
      }
      delete params.searchMemberName
      delete params.billEndDate
      delete params.memberType
      delete params.pageNum
      delete params.pageSize
      this.exportBtnLoading = true
      this.exportExcelPublic({
        api: 'venueAbnormalListExport',
        params
      }).finally(() => {
        this.exportBtnLoading = false
      })
    },
    // 提交列设置数据
    handleOrderList() {
      this.colSettings.visible = false
      this.updateIndexDB()
      this.activityListField = this.dialogColumnData
    },
    // 打开列设置弹框
    openColSettings() {
      this.getIndexDB(this.activityListField)
      this.colSettings.visible = true
    },
    // 复原缺省
    clickDel() {
      this.oldCol.map(item => {
        this.dialogColumnData[item.label] = true
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tips-box {
	position: absolute;
	right: 10px;
	top: 50%;
	margin-top: -12px;
}
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
}
::v-deep .el-table__fixed-footer-wrapper .cell,
::v-deep .el-table__footer-wrapper .cell {
	height: 100%;
	padding: 0 !important;
	margin: 0 !important;
	> div {
		height: 100%;
	}
}
::v-deep .footer_count_row {
	min-height: 50px;
	height: 50%;
	display: flex;
	font-weight: 700;
	padding: 5px 0;
	align-items: center;
	flex-direction: column;
	justify-content: center;
}
::v-deep .footer_count_row_border {
	border-top: 1px solid #ebeef5;
}
.input-with-select {
	width: 110px;
}
.ptop {
	padding-top: 2px;
	margin-left: 10px;
}
::v-deep .el-icon-question:after {
	font-size: 16px;
	margin-left: 0;
}
.arrowStyel {
	display: flex;
	justify-content: space-around;
}
.flex-box {
	display: flex;
	justify-content: flex-end;
	align-items: center;
	width: 100%;
	.export {
		height: 36px;
	}
}
</style>
